<script setup lang="ts">
import { useRouter } from 'vitepress';
import { OBreadcrumb, OBreadcrumbItem, OIcon } from '@opensig/opendesign';
import { type DocMenuNodeT } from '@/utils/tree.ts';
import { useSearchingStore } from '@/stores/common.ts';

import IconChevronRight from '~icons/app/icon-chevron-right.svg';
import { useLocale } from '@/composables/useLocale.ts';
import { useMenuStore } from '@/stores/menu.ts';
import { storeToRefs } from 'pinia';

const { $t } = useLocale();

const searchStore = useSearchingStore();

const menuStore = useMenuStore();
const { breadCrumbParams } = storeToRefs(menuStore);
const router = useRouter();

const handleClick = (item: DocMenuNodeT, index: number) => {
  let node = item;
  if (node) {
    while (breadCrumbParams.value.length > index + 1) {
      breadCrumbParams.value.pop();
    }

    while (node.children && node.children.length) {
      breadCrumbParams.value.push(node.children[0]);
      node = node.children[0];
    }
  }
  searchStore.isSearching = false;
  router.go(node.href);
};
</script>

<template>
  <OBreadcrumb class="breadcrumb">
    <template #separator>
      <OIcon>
        <IconChevronRight />
      </OIcon>
    </template>
    <!-- 文档聚合页 -->
    <OBreadcrumbItem href="/docs">{{ $t('docs.documentCenter') }}</OBreadcrumbItem>
    <!-- 模块 -->
    <!--    <OBreadcrumbItem v-if="tree?.root?.children?.[0]?.children?.[0]?.href"-->
    <!--                     @click="handleClick(tree.root.children[0], 0)">{{ docType }}-->
    <!--    </OBreadcrumbItem>-->
    <template v-if="!searchStore.isSearching">
      <!-- 其余节点 -->
      <OBreadcrumbItem
        v-analytics.addUrl="{ service: 'docs', properties: { type: 'breadcrumb', target: node.href } }"
        v-for="(node, i) in breadCrumbParams"
        @click="handleClick(node, i)"
        :key="node.id"
        >{{ node.label }}
      </OBreadcrumbItem>
    </template>
    <template v-else>
      <!-- 搜索最后一个节点显示：搜索结果 -->
      <OBreadcrumbItem>{{ $t('docs.searchResult') }}</OBreadcrumbItem>
    </template>
  </OBreadcrumb>
</template>

<style lang="scss" scoped>
.breadcrumb {
  margin-bottom: var(--layout-doc-padding-top);
  --breadcrumb-color-selected: var(--o-color-primary1);
  --breadcrumb-color-hover: var(--o-color-primary1);
  --breadcrumb-color-active: var(--o-color-primary1);

  :deep(.o-breadcrumb-item) {
    &:last-child {
      font-weight: 500;
    }
  }
  @include respond-to('phone') {
    display: none;
  }
}
</style>
